import { takeEvery, put, call } from 'redux-saga/effects'

import * as API from '../API/index.js'
import * as actions from '../actionTypes'

import { getLastModifyProject } from './project.js'

export function* getCurrentUser(action) {
    try {
        const data = yield call(API.getCurrentUser, {})
        if (data && data.userId) {
            yield put({ type: actions.SET_USER_INFO, payload: data })
        }
        yield call(getLastModifyProject)
    } catch (err) {
        console.log('err', err)
    }
}

export function* logoutUser(action) {
    try {
        const data = yield call(API.logoutUser, {})
        console.log(data)
        yield put({ type: actions.LOGOUT_USER_SUCCESS, payload: data })
    } catch (err) {
        console.log('err', err)
    }
}

export function* loginUser(action) {
    try {
        console.log(action.payload)
        const data = yield call(API.loginUser, action.payload)
        if (data.success) {
            yield put({ type: actions.LOGIN_USER_SUCCESS, payload: data.data })
        }
    } catch (err) {
        console.log('err', err)
    }
}

export function* phoneLogin(action) {
    try {
        console.log(action.payload)
        const data = yield call(API.phoneLogin, action.payload)
        if (data.success) {
            yield put({ type: actions.LOGIN_USER_SUCCESS, payload: data.data })
        }
    } catch (err) {
        console.log('err', err)
    }
}

export function* sendSMS(action) {
    try {
        console.log(action.payload)
        const data = yield call(API.sendSMSUrl, action.payload)
        if (data.success) {
            yield put({ type: actions.SEND_SMS_SUCCESS, payload: data.data })
        }
    } catch (err) {
        console.log('err', err)
    }
}

export function* registerUser(action) {
    try {
        console.log(action.payload)
        const data = yield call(API.registerUser, action.payload)
        if (data.success) {
            yield put({ type: actions.LOGIN_USER_SUCCESS, payload: data.data })
        }
    } catch (err) {
        console.log('err', err)
    }
}

export default function* watchLoadUsers() {
    yield takeEvery(actions.GET_CURRENT_USER, getCurrentUser)
    yield takeEvery(actions.LOGOUT_USER, logoutUser)
    yield takeEvery(actions.LOGIN_USER, loginUser)
    yield takeEvery(actions.SEND_SMS, sendSMS)
    yield takeEvery(actions.PHONE_LOGIN, phoneLogin)
    yield takeEvery(actions.REGISTER_USER, registerUser)
}



// WEBPACK FOOTER //
// ./src/sagas/users.js